using System;
using System.Windows.Forms;
using System.IO;
using ArchiveMe.Forms;
using ArchiveMe.Code;
using System.Xml;

namespace ArchiveMe.Forms
{
    public partial class frmConfig : Form
    {
        private string _configFileName;

        public frmConfig()
        {
            InitializeComponent();
        }

        private void ConfigForm_Load(object sender, EventArgs e)
        {
            SetDefaultValues();

            SetRegistrationStatus();

            // check if custom configuration file exists
            if (File.Exists(_configFileName))
            {
                try
                {
                    XmlTextReader reader = new XmlTextReader(_configFileName);
                    string node = "";
                    while (reader.Read())
                    {
                        switch (reader.NodeType)
                        {
                            case XmlNodeType.Element:
                                node = reader.Name;
                                break;
                            case XmlNodeType.Text:
                                if (node == "packLevel" && reader.HasValue)
                                {
                                    cbPackLevel.SelectedIndex = Convert.ToInt32(reader.Value) - 1;
                                }
                                if (node == "fileTheme" && reader.HasValue)
                                {
                                    txtFileName.Text = reader.Value;
                                }
                                break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error occoured", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }

        private void SetDefaultValues()
        {
            // set form title
            Text = string.Format("{0} {1} - Config", AppConfig.Name(), AppConfig.Version());

            // default pack level
            cbPackLevel.SelectedIndex = 4;
            // default file name theme
            txtFileName.Text = "{name}-{year}{month}{day}-{hr}{mm}";

            _configFileName = Application.ExecutablePath + ".cfn";
        }

        private void SetRegistrationStatus()
        {
            if (ContextMenuManager.IfExists("Directory", "Archive Me"))
            {
                SetIsRegistered();
            }
            else
            {
                SetIsNotResitered();
            }
        }

        private void SetIsRegistered()
        {
            lblRegisterStatus.Text = "Archive Me :) is registered!";
            btnUnregister.Enabled = true;
            btnRegister.Enabled = false;
        }

        private void SetIsNotResitered()
        {
            lblRegisterStatus.Text = "Archive Me :) is not registered!";
            btnUnregister.Enabled = false;
            btnRegister.Enabled = true;
        }

        private void aboutArchiveMeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form about = new frmAbout();
            about.Show();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void ConfigForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to exit?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                e.Cancel = true;
            }
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {
            // full path to self, %L is placeholder for selected file
            string menuCommand = string.Format("\"{0}\" \"%L\"", Application.ExecutablePath);

            // register the context menu
            ContextMenuManager.Register("Directory", "Archive Me", "Archive Me :)", menuCommand);

            MessageBox.Show("Archive Me has been registered!", "Archive Me");

            SetIsRegistered();
        }

        private void btnUnregister_Click(object sender, EventArgs e)
        {
            // unregister the context menu
            ContextMenuManager.Unregister("Directory", "Archive Me");

            MessageBox.Show("Archive Me has been unregistered!", "Archive Me");

            SetIsNotResitered();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                try
                {
                    xmlDoc.Load(_configFileName);
                }
                catch (FileNotFoundException)
                {
                    //if file is not found, create a new xml file
                    XmlTextWriter xmlWriter = new XmlTextWriter(_configFileName, System.Text.Encoding.UTF8);
                    xmlWriter.Formatting = Formatting.Indented;
                    xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                    xmlWriter.WriteStartElement("Root");
                    xmlWriter.Close();
                    xmlDoc.Load(_configFileName);
                }
                XmlNode root = xmlDoc.DocumentElement;
                if (root != null)
                {
                    root.RemoveAll();
                    XmlElement childNode = xmlDoc.CreateElement("packLevel");
                    XmlElement childNode2 = xmlDoc.CreateElement("fileTheme");
                    XmlText textNode = xmlDoc.CreateTextNode("pack");
                    XmlText textNode2 = xmlDoc.CreateTextNode("file");

                    root.AppendChild(childNode);
                    root.AppendChild(childNode2);
                    int level = cbPackLevel.SelectedIndex + 1;
                    textNode.Value = level.ToString();
                    childNode.AppendChild(textNode);
                    textNode2.Value = txtFileName.Text;
                    childNode2.AppendChild(textNode2);

                    xmlDoc.Save(_configFileName);

                    MessageBox.Show("Settings has been saved successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Error occoured! Please try again.", "Error occoured", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error occoured", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}